#!/usr/bin/python
'''
    Player for Google Music using gmusicapi

    $ URL: $
    $ Revision: $
    $ Date: $
    $ Author: $
    '''

import optparse
import sys
from os import path, environ, path, devnull
from gmusicapi import Mobileclient, Webclient
import pickle
import pyaudio

APPNAME = "gmusic_player"
DEV_ID = "0x3c64b5b98b4dcce7"
CHUNK = 1024

if sys.platform == 'darwin':
    from AppKit import NSSearchPathForDirectoriesInDomains
    # http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSSearchPathForDirectoriesInDomains
    # NSApplicationSupportDirectory = 14
    # NSUserDomainMask = 1
    # True for expanding the tilde into a fully qualified path
    appdata = path.join(NSSearchPathForDirectoriesInDomains(14, 1, True)[0], APPNAME)
elif sys.platform == 'win32':
    appdata = path.join(environ['APPDATA'], APPNAME)
else:
    appdata = path.expanduser(path.join("~", "." + APPNAME))

def play(stream):
    with open(os.devnull, 'w') as temp:
        proc =  subprocess.Popen(["mplayer", "-noconfig", "all","%s" % song], stdin=subprocess.PIPE, stdout=temp, stderr=temp)
        return proc

def gmusic_player(options):
    '''gmusic_player:
    Player for Google Music using gmusicapi'''
    print 'gmusic_player'
    print 'Using gmusicapi version ', 

    try:
        login_file = open(options.login_file, 'r')
        username = login_file.readline()
        print 'User: ', username
        password = login_file.readline()
        login_file.close()
    except:
        print 'Login file not found'
        raise

    #api = Mobileclient()
    api = Webclient()
    login_result = api.login(username, password)
    print 'Login result: ', login_result
    #login_result = web_api.login(username, password)
    #print 'Login result: ', login_result

    print api.get_registered_devices()

    if (options.update_library == True) or (not path.exists(options.library_file)):
        library = api.get_all_songs()
        print 'Retrieved library'
        library_file = open(options.library_file, 'w')
        pickle.dump(library, library_file)
        library_file.close()
    else:
        library_file = open(options.library_file, 'r')
        library = pickle.load(library_file)
        library_file.close()
        print 'Loaded library'

    
    test_tracks = [track for track in library if track['artist'] == 'Beach House']

    # Show some info about a song. There is no guaranteed order;
    # this is essentially a random song.
    first_song = test_tracks[0]
    print "The first song I see is '{}' by '{}'.".format(
        first_song['title'].encode('utf-8'),
        first_song['artist'].encode('utf-8'))

    song_id = first_song['id']
    print repr(first_song)
    print '\n\n\n'
    stream = api.get_stream_audio(first_song['id'])
    playing = play(stream)

    
if __name__ == "__main__":
    parser = optparse.OptionParser(version='%prog version $ Rev: $')

    login_options_group = optparse.OptionGroup(parser, 'Login')
    login_options_group.add_option( '--login-file', 
                                    dest='login_file',
                                    default=path.join(appdata, 'gmusic_player.login'),
                                    metavar='<filename>',
                                    action='store',
                                    help='specify login details file [%default]')
    parser.add_option_group(login_options_group)

    library_options_group = optparse.OptionGroup(parser, 'Library')
    library_options_group.add_option(   '--update-library', '-u',
                                        dest='update_library',
                                        default=False,
                                        action='store_true',
                                        help='update library on login [%default]')
    library_options_group.add_option(   '--library-file',
                                        dest='library_file',
                                        default=path.join(appdata, 'gmusic_player_library.lib'),
                                        action='store',
                                        help='temporary library cache file path [%default]')
    parser.add_option_group(library_options_group)

    (options, args) = parser.parse_args()

    gmusic_player(options)

# End of File